<!DOCTYPE html>
<html lang="">
<head>
  <meta charset="UTF-8">
  <title>文本转换为拼音HTML</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<style>
    * {
        font-size: 14px;
    }

    .form {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .form textarea {
        outline: none;
        padding: 5px;
        border: 1px solid #ccc;
        border-radius: 6px;
    }

    .form .label {

    }

    .action {
        text-align: center;
        padding: 10px;
    }

    .btn {
        background: royalblue;
        border-radius: 4px;
        padding: 5px 20px;
        border: 1px solid royalblue;
        color: #fff;
        cursor: pointer;
    }

    .btn :hover {
        opacity: .8;
    }

    .btn :active {
        opacity: .8;
    }

    .content {
        text-align: justify;
    }

    .word {
        padding: 10px 5px;
        display: inline-block;
    }
</style>
<body>
<div class="container">
  <div class="form">
    <label class="label" for="put">输入文本：</label>
    <textarea name="" id="put" cols="30" rows="10"></textarea>
  </div>
  <div class="action">
    <button id="btn-transform" class="btn">转换</button>
  </div>
  <div id="content" class="content">
  </div>
</div>
<script>
  // const textarea = document.querySelector("#put");
  // const btnTransForm = document.querySelector("#btn-transform");
  // btnTransForm.addEventListener('click', () => {
  //   console.log(textarea.value);
  // })
</script>
<script type="module">
  import pinyin from "pinyin";

  // 将文本转换为带有拼音的HTML字符串
  function convertToHTML(text) {
    const words = text.split('');
    let html = '';

    for (let word of words) {
      // 获取每个字的拼音数组
      const pinyinArray = pinyin(word, {
        // style: pinyin.STYLE_NORMAL,
        segment: "@node-rs/jieba",
      });

      // 将拼音数组转换为拼音字符串
      const pinyinString = pinyinArray.map((item) => item[0]).join(' ');

      // 构建HTML标签
      html += `<span class="word"><ruby>${word}<rt>${pinyinString}</rt></ruby></span>`;
    }

    return html;
  }

  const textarea = document.querySelector("#put");
  const content = document.querySelector("#content");
  const btnTransForm = document.querySelector("#btn-transform");
  btnTransForm.addEventListener('click', () => {
    console.log(textarea.value);
  })
  content.append(convertToHTML(textarea.value));
</script>
</body>
</html>
